<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>PCM player</title>
</head>

<body>
  <script src="//cdn.jsdelivr.net/npm/eruda"></script>
  <script>eruda.init();</script>
  <div id="container"
       style="width: 400px; margin: 0 auto;">
    <button onclick="loadPCM()">PlayPCM</button>
    <input type="range"
           max="1"
           value="0.1"
           min="0"
           id="range"
           onchange="changeVolume(event)"
           step="0.1"><br />
    <button onclick="pause()">PausePlaying</button>
    <button onclick="continuePlay()">ContinuePlaying</button>
    <br><br><br><br><br><br>
    <div>note:please allow browser load mixed content</div>
    <div>注:如果无法播放，请尝试允许本页面加载混合内容(http)</div>
    <br>
    <a href="https://stackoverflow.com/questions/18321032/how-to-get-chrome-to-allow-mixed-content">How to get Chrome
      to allow mixed content?</a>
  </div>

  <script src="https://unpkg.com/pcm-player"></script>
  <script>
    let player
    function loadPCM() {
      // 这是我搭载自己服务器上的server端，用来接收pcm数据
      // 如果起了example里面的本地server端，改成对应的ws地址就行了
      var socketURL = 'ws://192.210.136.64:8080';

      player = new PCMPlayer({
        inputCodec: 'Int16',
        channels: 2,
        sampleRate: 44100,
        flushTime: 200,
        onstatechange: (node, event, type) => {
          console.log('type', node, event, type)
        },
        onended: (node, event) => {
          console.log('end fire', node, event)
        }
      });

      var ws = new WebSocket(socketURL);
      ws.binaryType = 'arraybuffer';
      ws.addEventListener('message', function (event) {
        // 可以传 ArrayBuffer 或者 任意TypedArray
        player.feed(event.data);
      });
    }

    function changeVolume(e) {
      player.volume(document.querySelector('#range').value)
    }
    async function pause() {
      await player.pause()
    }
    function continuePlay() {
      player.continue()
    }
  </script>
</body>

</html>